<template>
  <div style="height: 6vh;background-color:#fff;padding: 10px 20px;">
    <span style="line-height:60px;font-size:20px;">门店管理</span>
    <el-button type="primary" style="float: right;margin-top: 10px;"
               @click="save">保存
    </el-button>
  </div>
  <el-card style="margin: 20px;">
    <el-form>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="门店名称:">
            <el-input placeholder="请输入门店名称" v-model="saveCinema.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话:">
            <el-input placeholder="请输入联系电话" v-model="saveCinema.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="所属地区:" >
            <el-cascader
                    size="large"
                    clearable
                    ref="cascader"
                    :options="options"
                    v-model="selectedOptions"
                    @change="handleChange"
                >
                </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址:" >
            <el-input placeholder="请输入详细地址" v-model="saveCinema.address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="门店图片:">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="9"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl"/>
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所需租金">
            <el-input placeholder="请输入租金" v-model="saveCinema.rent"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
    >
      <el-menu-item index="1">影厅管理</el-menu-item>
      <el-menu-item index="2">店员管理</el-menu-item>
    </el-menu>
    <div v-if="activeIndex === '1'">
      <h2>影厅管理</h2>
      <!-- 影厅管理的内容 -->
      <el-table :data="halls" border stripe>
        <el-table-column type="index" width="50">
          <template #header>
            <el-button type="primary" @click="addhall">添加</el-button>
          </template>
          <el-table-column type="index" width="55">
          </el-table-column>
          <el-table-column prop="name" label="影厅名称">
          </el-table-column>
          <el-table-column prop="seatNum" label="座位数"></el-table-column>
          <el-table-column prop="type" label="影厅类型"></el-table-column>
          <el-form-item label="影厅状态">
            <el-radio-group>
              <el-radio border label="启用" value="1" style="margin:0;"></el-radio>
              <el-radio border label="禁用" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-table-column prop="location" label="具体位置"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button link type="primary" @click="edithall(scope.row, scope.$index)">编辑</el-button>
              <el-button link type="primary" @click="deletehall(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="activeIndex === '2'">
      <h2>店员管理</h2>
      <!-- 店员管理的内容 -->
    </div>

    <!--新建影厅的弹窗-->
    <el-dialog
        :title="dialogTitle"
        style="width: 1000px;padding: 40px;"
        v-model="dialogVisible1"
        :before-close="handleClose"
    >
      <el-form label-position="top" label-width="80px">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="影厅名称:">
              <el-input placeholder="请输入影厅名称" v-model="hallForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="影厅类型">
              <el-select placeholder="请选择" v-model="hallForm.type">
                <el-option-group>
                  <el-option label="IMAX厅" value="IMAX厅"></el-option>
                  <el-option label="CGS中国巨幕厅" value="CGS中国巨幕厅"></el-option>
                  <el-option label="杜比全景声厅" value="杜比全景声厅"></el-option>
                  <el-option label="RealD厅" value="RealD厅"></el-option>
                  <el-option label="4DX厅" value="4DX厅"></el-option>
                  <el-option label="DTS:X 临境音厅" value="DTS:X 临境音厅"></el-option>
                  <el-option label="儿童厅" value="儿童厅"></el-option>
                  <el-option label="4K厅" value="4K厅"></el-option>
                  <el-option label="4D厅" value="4D厅"></el-option>
                  <el-option label="60帧厅" value="60帧厅"></el-option>
                  <el-option label="巨幕厅" value="巨幕厅"></el-option>
                  <el-option label="激光厅" value="激光厅"></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="具体位置:">
              <el-input placeholder="请输入具体位置" v-model="hallForm.location"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveHall">保存</el-button>
      </template>
    </el-dialog>


  </el-card>
</template>

<script setup>
import {codeToText, regionData} from 'element-china-area-data'
import {ref, onMounted} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const saveCinema = ref({
  name: '',
  address: '',
  phone: '',
  rent: ''
})
const activeIndex = ref('1');
//定义变量用来保存图片提交的后端接口地址
const handleSelect = (key) => {
  activeIndex.value = key;
};
const options = ref(regionData)
const selectedOptions = ref([])

const handleChange = () => {
  console.log('选中的地区代码:', selectedOptions.value)
  
  // 确保选择了完整的三级地址
  if (selectedOptions.value && 
      selectedOptions.value.length === 3 && 
      selectedOptions.value[2]) {
    // 只保存第三级（区级）地址
    saveCinema.value.city = codeToText[selectedOptions.value[2]]
    console.log('保存的地区:', saveCinema.value.city)
  } else {
    saveCinema.value.city = ''
  }
}



/*图片上传相关代码开始*/
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload')
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  //1.得到要删除的图片路径 uploadFile 就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!')
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
  console.log('预览图片URL:', dialogImageUrl.value)
}
/*图片上传相关代码结束*/

// 定义方法
const save = () => {
  // 验证影院图片
  if(fileList.value.length === 0){
    ElMessage.error('请上传影院图片!')
    return
  }

  // 验证是否有影厅数据
  if(halls.value.length === 0) {
    ElMessage.error('请至少添加一个影厅!')
    return
  }

  // 处理图片路径
  let imgUrl = ""
  let fileLength = fileList.value.length
  for(let i = 0; i < fileLength; i++){
    let file = fileList.value[i].response.data
    imgUrl += file + ','
    if(i === fileLength-1){
      imgUrl = imgUrl.substring(0, imgUrl.length-1)
    }
  }
  
  // 准备请求数据
  const requestData = {
    id: route.query.id,
    name: saveCinema.value.name,
    address: saveCinema.value.address,
    city: saveCinema.value.city,
    phone: saveCinema.value.phone,
    rent: saveCinema.value.rent,
    img: imgUrl,
    halls: halls.value.map(hall => ({
      name: hall.name,
      type: hall.type, 
      location: hall.location,
      status: hall.status
    }))
  }

  console.log('发送的数据:', requestData)

  // 修改这里：统一使用 save 接口
  const url = `${BASE_URL}/v1/cinemas/save`

  // 发送保存请求
  axios.post(url, requestData, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then((response) => {
      console.log('服务器响应:', response.data)
      if (response.data.code === 2000) {
        ElMessage.success('保存成功!')
        router.push('/Information')
      } else {
        ElMessage.error(response.data.msg || '保存失败!')
      }
    })
    .catch(error => {
      console.error('HTTP Status:', error.response?.status)
      console.error('错误响应数据:', error.response?.data)
      console.error('请求配置:', error.config)
      ElMessage.error('保存失败，请检查数据!')
    })
}
const dialogVisible1 = ref(false)
const dialogTitle = ref('新增影厅')
const halls = ref([])

const hallForm = ref({
  name: '',
  type: '',
  location: '',
  status: '1'
})
const saveHall = () => {
  if (isEdit.value) {
    halls.value[editIndex.value] = { ...hallForm.value }
  } else {
    halls.value.push({
      name: hallForm.value.name,
      type: hallForm.value.type,
      location: hallForm.value.location,
      status: hallForm.value.status
    })
  }
  dialogVisible1.value = false
  hallForm.value = {}
  console.log(hallForm.value)
}

// 添加删除方法
const deletehall = (index) => {
  if (confirm('您确认要删除本影厅吗?')) {
    halls.value.splice(index, 1)
  }
}

// 添加编辑方法
const isEdit = ref(false)
const editIndex = ref(-1)

const edithall = (row, index) => {
  isEdit.value = true
  editIndex.value = index
  // 复制要编辑的数据到表单
  hallForm.value = { ...row }
  dialogVisible1.value = true
  dialogTitle.value = '编辑影厅'
}

const handleClose = () => {
  if (confirm('您确认要关闭本窗口吗?')) {
    dialogVisible1.value = false
    isEdit.value = false
    editIndex.value = -1
    // 清空表单
    hallForm.value = {
      name: '',
      type: '',
      location: '',
      status: 1
    }
  }
}
const addhall = () => {
  isEdit.value = false
  editIndex.value = -1
  dialogVisible1.value = true
  dialogTitle.value = '新增影厅'
  // 清空表单
  hallForm.value = {
    name: '',
    type: '',
    location: '',
    status: 1
  }
}

// 在 onMounted 中添加加载数据的逻辑
onMounted(() => {
  const id = route.query.id
  console.log('当前影院ID:', id)

  if (id) {
    axios.get(`${BASE_URL}/v1/cinemas/select`, {
      params: { id: id }
    })
      .then((response) => {
        console.log('获取到的完整响应:', response.data)
        
        if (response.data.code === 2000 && response.data.data.length > 0) {
          saveCinema.value = response.data.data[0]
          console.log('影院基础数据:', saveCinema.value)
          
          // 修改地区数据回显处理
          if (saveCinema.value.city) {
            // 遍历省份数据找到对应的区域
            for (const province of options.value) {
              for (const city of province.children || []) {
                for (const district of city.children || []) {
                  if (district.label === saveCinema.value.city) {
                    selectedOptions.value = [
                      province.value,
                      city.value,
                      district.value
                    ]
                    console.log('回显地区选项:', selectedOptions.value)
                    break
                  }
                }
              }
            }
          }
          
          // 简化图片处理逻辑
          if (saveCinema.value.img) {
            console.log('从后端获取的原始图片路径:', saveCinema.value.img)
            const imgs = saveCinema.value.img.split(',')
            console.log('分割后的图片数组:', imgs)
            
            fileList.value = imgs.map(img => ({
              name: img.split('/').pop(),
              url: img.startsWith('http') ? img : `${BASE_URL}${img}`, // 直接拼接路径
              response: { data: img }
            }))
            console.log('最终设置的文件列表:', fileList.value)
          } else {
            console.log('没有获取到图片数据')
          }

          // 获取影厅数据
          return axios.get(`${BASE_URL}/v1/hall/select`, {
            params: { cinemaId: id }
          })
        }
      })
      .then(hallResponse => {
        if (hallResponse && hallResponse.data.code === 2000) {
          halls.value = hallResponse.data.data
          console.log('设置的影厅数据:', halls.value)
        }
      })
      .catch(error => {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败，请稍后重试!')
      })
  }
})
</script>

<style scoped>

</style>